const fs = require('fs');
const path = require('path');
const { mock, Random } = require('mockjs');

function generate() {
  [
    { file: 'data-50.json', num: 50 },
    // { file: 'data-200.json', num: 200 },
    // { file: 'data-2000.json', num: 2000 },
  ].forEach((item) => {

    const statusOptions = ['primary', 'success', 'warn', 'error', 'secondary'];

    const getRandomStatusList = () => {
      const count = Math.ceil(Math.random() * 3);
      const array = [];
      while (array.length < count) {
        const index = parseInt(Math.random() * statusOptions.length - 1);
        const item = statusOptions[index];
        if (array.indexOf(item) === -1) {
          array.push(item);
        }
      }
      return array;
    };

    const getRandomDateList = () => {
      const count = Math.ceil(Math.random() * 3);
      const array = [];
      while (array.length < count) {
        const value = Random.date();
        if (array.indexOf(value) === -1) {
          array.push(value);
        }
      }
      return array;
    };

    fs.writeFileSync(path.resolve(__dirname, `./${item.file}`), JSON.stringify(
      (() => {
        const { array } = (mock({
          [`array|${item.num}`]: [
            {
              "id|+1": 0,
              color: '@color',
              name: '@first',
              "star|0-10": 5,
              "flag": () => Math.random() > 0.5 ? 'Y' : 'N',
              "size|40-80": 60,
              addr: '@county(true)',
              url: '@url',
              domain: '@domain',
              protocol: '@protocol',
              email: '@email',
              ip: '@ip',

              tel: (() => {
                const prefix = ['139', '136', '132', '181', '172', '191'];
                const getNumber = () => {
                  let arr = [];
                  while (arr.length < 8) {
                    arr.push(parseInt(Math.random() * 9));
                  }
                  return arr.join('');
                };
                return () => {
                  let randomPrefix = Math.min(Math.floor(Math.random() * prefix.length), prefix.length - 1);
                  return prefix[randomPrefix] + getNumber();
                };
              })(),
              'num|0-999999': 0,
              'float|0-1000.2': 0,
              'percent|0.4': 0,

              status: () => statusOptions[parseInt(Math.random() * statusOptions.length - 1)],
              statusList: getRandomStatusList,
              statusArrayJson: () => JSON.stringify(getRandomStatusList()),
              statusArrayString: () => getRandomStatusList().join(','),

              date: '@date',
              dateList: getRandomDateList,
              dateArrayJson: () => JSON.stringify(getRandomDateList()),
              dateArrayString: () => getRandomDateList().join(','),
            }
          ]
        }));
        array.forEach(item => {
          /*dateNumber测试值格式化*/
          item.dateNumber = item.date.replace(/-/g, '');

          /*startDate以及endDate测试日期范围*/
          const startDate = Random.date();
          let endDateObj = new Date(new Date(startDate.replace(/-/g, '/')).getTime() + (24 * 60 * 60 * 1000) * (parseInt(Math.random() * 500)));
          const endDate = `${endDateObj.getFullYear()}-${String(endDateObj.getMonth() + 1).padStart(2, '0')}-${String(endDateObj.getDate()).padStart(2, '0')}`;
          item.startDate = startDate;
          item.endDate = endDate;

          /*startDatetime以及endDatetime测试日期时间范围*/
          const startDatetime = `${Random.date()} ${Random.time()}`;
          endDateObj = new Date(new Date(startDatetime.replace(/-/g, '/')).getTime() + parseInt(Math.random() * 864000000));
          item.startDatetime = startDatetime;
          item.endDatetime = [
            endDateObj.getFullYear(),
            endDateObj.getMonth() + 1,
            endDateObj.getDate(),
          ].map(i => String(i).padStart(2, '0')).join('-') + ' ' + [
            endDateObj.getHours(),
            endDateObj.getMinutes(),
            endDateObj.getSeconds(),
          ].map(i => String(i).padStart(2, '0')).join(':');

          /*测试time*/
          item.time = Random.time();
          item.timeNumber = item.time.replace(/:/g, '');

          /*startTime以及endTime测试时间范围*/
          let dateObj = new Date();
          const [hour, minute, second] = item.time.split(':');
          dateObj.setHours(hour);
          dateObj.setMinutes(minute);
          dateObj.setSeconds(second);
          const startTimestamp = dateObj.getTime();
          dateObj.setHours(23);
          dateObj.setMinutes(59);
          dateObj.setSeconds(59);
          const endTimestamp = dateObj.getTime();
          item.startTime = item.time;
          dateObj = new Date((Math.random() * (endTimestamp - startTimestamp)) + startTimestamp);
          item.endTime = [dateObj.getHours(), dateObj.getMinutes(), dateObj.getSeconds()].map(i => String(i).padStart(2, '0')).join(':');

        });
        return array;
      })(),
      null,
      2,
    ))
    ;
  });
}

generate();
